package com.topwalk.datacollect.factoty;

import com.topwalk.datacollect.config.ApplicationContextProvider;
import com.topwalk.datacollect.enumI.FactoryEnum;
import com.topwalk.datacollect.enumI.ServerEnum;
import com.topwalk.datacollect.serverResult.BaseModelDecorate;
import com.topwalk.datacollect.server.BaseServer;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.stereotype.Component;

import java.beans.Introspector;

@Component
public class ServerFactory extends BaseFactory {
    private final String factoryCode = FactoryEnum.SERVER.toString();


    //第二个参数是：BaseServer处理的结果期望的返回类型
    public <T> BaseServer<T> getServerImpl(String serverName, Class<T> clazz) {
        boolean flag = checkContainServerEunm(serverName);
        Object bean;
        if(flag){
            try {
                //根据spring源码，处理serverName。
                // org.springframework.context.annotation.AnnotationBeanNameGenerator.generateBeanName --> java.beans.Introspector.decapitalize
                serverName = Introspector.decapitalize(serverName);
                bean = ApplicationContextProvider.getBean(serverName + "ServiceImpl");
            } catch (NoSuchBeanDefinitionException e) {
                //这个try catch纯粹是为了业务。由于是融合的接收程序，现在在写MTP的处理，考虑到兼容其他接收处理，如果没找到对应的处理程序，则按照原样执行
                return null;
            }
            return (BaseServer<T>) bean;
        }else {
            return null;
        }

    }

    @Override
    public String getCode() {
        return this.factoryCode;
    }

    //检查serverName是否在ServerNum中
    private boolean checkContainServerEunm(String serverName){
        if(serverName == null){
            throw new RuntimeException("serverName不能为空。");
        }

        boolean flag = false;
        ServerEnum[] values = ServerEnum.values();
        for (ServerEnum serverEnum : values){
            if(serverName.equalsIgnoreCase(serverEnum.toString())){
                flag = true;
                break;
            }
        }
        return flag;
    }
}
